import React, { PureComponent } from 'react';
// import PropTypes from 'prop-types';
import G2 from '@antv/g2';
import { DataSet } from '@antv/data-set';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import classNames from 'classnames';

import { isEqual } from 'lodash';
import { isNotEmptyArray } from '../../../utils/utils';
import '../index.less';

/*const primaryColor = '#2F9CFF';
const infoColor = '#53A0FD';*/

export default class BarV3 extends PureComponent {
  /*static defaultProps = {};

  state = {};

  componentWillMount() {

  }*/
  componentDidMount() {
    this.initChart();
    window.addEventListener('resize', this.resize);
  }

  componentWillReceiveProps(nextProps) {
    if (!isEqual(this.props, nextProps)) {
      this.initChart(nextProps);
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize);
    this.data = null; // 解决路由变化时，回到本页面时，图表未清除的问题
    if (this.chart) {
      this.chart.destroy();
    }
    this.resize.cancel();
  }
  @Bind()
  @Debounce(200)
  resize() {
    if (!this.node) {
      return;
    }
    this.renderChart();
  }

  handleRef = (n) => {
    this.node = n;
  }

  /**
   * 延迟加载，避免样式还没渲染完成导致 this.node.clientHeight 获取时值不对
   */
  @Debounce(10)
  initChart(nextProps) {
    const {
      x, y, data = [],
    } = nextProps || this.props;

    if (!x || !y) {
      throw new Error('x or y not defined');
    }
    if (!isNotEmptyArray(data)) {
      return;
    }
    this.data = data.map(e => ({
      ...e,
      [y]: Number(e[y]),
    }));
    this.renderChart(nextProps);
  }

  renderChart(nextProps) {
    const {
      height = this.node.clientHeight, x, y, yAlias, mutilBar = false, groupName = x,
      transpose = false, needSort = false, xFormatter,
      /*color = primaryColor, pointColor = infoColor,
      yMin = 0, pointRadius = 4, pointShape = 'circle',*/
      animate = true, padding = [20, 20, 40, 48],
    } = nextProps || this.props;

    if (this.chart) {
      this.chart.clear();
    }
    if (this.node) {
      this.node.innerHTML = '';
    }

    const ds = new DataSet();
    const dv = ds.createView();
    dv.source(this.data);
    if (needSort) {
      dv.transform({
        type: 'sort',
        callback(a, b) { // 排序依据，和原生js的排序callback一致
          return a[y] - b[y] > 0;
        },
      });
    }
    const chart = new G2.Chart({
      container: this.node,
      forceFit: true,
      height,
      animate,
      padding,
    });
    chart.source(dv);
    chart.scale(`${y}`, {
      nice: true,
      tickCount: 5,
      alias: yAlias,
    });
    chart.axis(`${x}`, {
      label: {
        offset: 12,
        formatter: xFormatter,
      },
    });
    if (transpose) {
      chart.coord().transpose();
    }
    if (mutilBar) {
      // 分组柱形图，利用 .color(groupName) 来区分出来，
      // 未设置时 groupName 值为 'x'，此时柱形图层叠在一起，即一根柱子
      // 在遵循职能单一的原则上，推荐使用 GroupedBar 组件进行分组柱状图的绘制
      // 其data 数组元素更少，体积更小，可进行其他配置
      chart.intervalDodge().position(`${x}*${y}`).color(`${groupName}`);
    } else {
      chart.interval().position(`${x}*${y}`).color(`${x}`);
    }

    this.chart = chart;
    chart.render();
  }

  render() {
    const { data } = this.props;
    // 增加图表无数据时的显示，优化体验
    const noDataClass = classNames({ noData: !isNotEmptyArray(data) });
    return (
      <div ref={this.handleRef} className="chart">
        <div className={noDataClass}>暂无数据</div>
      </div>
    );
  }
}
